import * as cheerio from "cheerio";
import axios from  "axios";
import {default as iconv } from "iconv-lite"
import fs from "fs"
// @ts-ignore
import {timeStampToTime} from "./common.js";
// @ts-ignore
import async from "async";
import path from "path";

// @ts-ignore
async function getHtml(url) {
    const res = await axios({
        url,
        responseType: 'stream' // 以数据流的方式输出
    })

    // 返回一个promise实例对象
    return new Promise(resolve => {
        const chunks: any[] | readonly Uint8Array[] = []
        res.data.on('data', (chunk: any) => {
            // @ts-ignore
            chunks.push(chunk)
        })
        res.data.on('end', () => {
            const buffer = Buffer.concat(chunks)
            const str = iconv.decode(buffer, 'gbk')
            resolve(str)
        })
    })
}

async function fetchSingleStockData(stock: { code: any; }) {
    console.log("stock.code",stock.code)
    const url = `http://doctor.10jqka.com.cn/${stock.code}/`;
    const html = await getHtml(url)
    // @ts-ignore
    const $ = cheerio.load(html, { decodeEntities: false })    // decodeEntities:false设置了不会出现中文乱码。尽量都加上以防万一
    let trendRate = ""; // 趋势判断
    let shortTrend = ""; // 短期趋势
    let interTrend = ""; // 中期趋势
    let longTrend = ""; // 长期趋势
    let averagePrice = ""; // 平均成本
    let supportPrice = ""; // 支撑价格
    let pressurePrice = ""; // 压力价格
    let techSummary = ""; // 技术面总结
    const detail: { title: string; content: string; }[] = []; // 详细信息

    // 总体评价
    trendRate = $('.value_bar .cur').html()
    // 短、中、长期趋势
    const trendListHTML = $('.value_info ul').children();
    trendListHTML.each((i, ele)=>{
        if(i<3){
            const text =  $(ele).find("p").text()
            if(i===0){
                shortTrend = text;
            }else if(i===1){
                interTrend = text;
            }else if(i===2){
                longTrend = text;
            }
        }
    })
    // 平均成本
    const averagePriceHTML = $('.nx_items .box3 .hd2 strong').html();

    averagePrice = averagePriceHTML.replace(/[^0-9.]/g,'')

    // 支撑价格
    const pressurePriceHTML =$('[stat=f10_nc_2] .hd2').html();
    pressurePrice= pressurePriceHTML.match(/(?<=压力位为).*(?=元，)/g)[0];

    // 压力价格
    const supportHTML =$('[stat=f10_nc_2] .hd2').html();
   supportPrice= supportHTML.match(/(?<=支撑位为).*(?=元)/g)[0];

    // 技术面分析
    techSummary = $('.cnt.showlevel2').html();


    // 详细
    const title = ["技术面分析", "市场表现","压力支撑","多空趋势","?","资金流向","主力控盘","行业资金","机构持仓","行业走势","行业面诊断","盈利能力","成长能力","营运能力","现金流能力","短期偿债能力","长期偿债能力","机构评级","机构预测"]
    $('.nx_items .box3 .hd2').each((i, elem)=> {
        const content = $(elem).html()
        detail.push({
            title:title[i],
            content,
        });
    });
    const stockInfo = {
        trendRate,
        shortTrend,
        interTrend,
        longTrend,
        techSummary,
        averagePrice,
        supportPrice,
        pressurePrice,
        detail,
    }
    Object.assign(stock, stockInfo)
    return stock;
}
 const fetchAllStockData =  async (_allStockInfo: any)=>{
    for (const stock of _allStockInfo) {
        await  fetchSingleStockData(stock);
    }
     fs.mkdirSync("../data/", {recursive: true,})
     const time = timeStampToTime(new Date().valueOf(), "YMD")
     const saveFileName = path.join(__dirname, `../data/${time}.json`);
     fs.writeFileSync(saveFileName, JSON.stringify(_allStockInfo));

}

export default fetchAllStockData
